<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div
      class="filter-container"
      style="display: flex; justify-content: flex-start"
    >
      <el-input
        @keyup.enter.native="handleFilter"
        clearable
        v-model="listQuery.userId"
        type="number"
        style="width: 200px; margin-right: 15px"
        placeholder="请输入Id"
      ></el-input>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.nickName"
        style="width: 200px; margin-right: 15px"
        placeholder="昵称"
      >
      </el-input>
      <el-input
        clearable
        @keyup.enter.native="handleFilter"
        v-model="listQuery.userPhone"
        style="width: 200px; margin-right: 15px"
        placeholder="手机号"
      >
      </el-input>
      <el-select
        placeholder="用户状态"
        style="width: 200px; margin-right: 15px"
        v-model="listQuery.isFlag"
        clearable
      >
        <el-option
          v-for="item in options1"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <!-- 2022.09.07  合并为时间日期选择器 -->
      <el-date-picker
        v-model="dateTime"
        type="datetimerange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:00"
        @change="getDateTime"
      >
      </el-date-picker>

      <!-- <el-form-item label="开始日期："> -->
      <!-- <el-date-picker
            v-model="listQuery.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:00"
            placeholder="选择开始日期"
            style="width: 200px;margin-right:15px;" class="filter-item"
          ></el-date-picker> -->
      <!-- </el-form-item> -->
      <!-- <el-form-item label="结束日期："> -->
      <!-- <el-date-picker
            v-model="listQuery.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:00"
            placeholder="选择结束日期"
             style="width: 200px;margin-right:15px;" class="filter-item"
          ></el-date-picker> -->
      <!-- </el-form-item> -->
      <br />
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
        style="margin-left: 15px"
        >搜索</el-button
      >
      <el-button
        type="primary"
        class="filter-item"
        @click="handleDownload"
        icon="el-icon-download"
        :loading="downloadLoading"
        >导出</el-button
      >
    </div>

    <!-- table 表格 -->
    <el-table
      :data="list"
      v-loading="loading.list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
      max-height="830"
    >
      <el-table-column label="序号" prop="index" align="center" width="80px" />
      <el-table-column label="id" prop="userId" align="center" />
      <el-table-column label="昵称" prop="nickName" align="center" />
      <el-table-column label="手机号" prop="userPhone" align="center" />
      <el-table-column label="地址" prop="address" align="center" />
      <el-table-column label="金额(元)" prop="amountInfo" align="center" />
      <el-table-column
        label="赠送金额(元)"
        prop="givenAmountInfo"
        align="center"
      />
      <el-table-column label="用户类型" prop="userTypeInfo" align="center" />
      <el-table-column label="用户状态" prop="isFlagInfo" align="center" />
      <el-table-column label="创建时间" prop="ctime" align="center" />
      <!--  -->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            v-if="scope.row.isFlag == 2"
            @click="changeStatus(scope.row.userId, 1, '')"
            >启用
          </el-button>
          <el-button
            size="mini"
            type="warning"
            v-else
            @click="changeStatus(scope.row.userId, 2, '')"
            >禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.offset"
        :page-sizes="[10, 20, 30, 40, 100, 300, 500, 5000, 10000]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import { getList, updateIsFlagUsers } from "@/api/user";
import { validatePhone } from "@/utils/validate";
import BackToTop from "@/components/BackToTop";
import VePie from "v-charts/lib/pie";
import { parseTime } from "@/utils";
export default {
  name: "user_list",
  components: {
    BackToTop,
    VePie,
  },
  data() {
    //  var validatePass = (rule, value, callback) => {
    //     if (!validatePhone(value)) {
    //       return callback(new Error('请填写正确的手机号码'));
    //     } else {
    //       callback();
    //     }
    //   };
    return {
      dateTime: "",
      total: 0,
      // 搜索框信息
      listQuery: {
        offset: 1,
        limit: 10,
        nickName: "",
        userPhone: "",
        isFlag: "",
        startTime: "",
        endTime: "",
        // 导出文件部分信息
        userId: "",
        amount: "",
        givenAmount: "",
        userType: "",
        ctime: "",
      },
      // 用户状态
      options1: [
        {
          value: "1",
          label: "启用",
        },
        {
          value: "2",
          label: "禁用",
        },
      ],
      // 用户类型
      options2: [
        {
          value: "1",
          label: "普通用户",
        },
        {
          value: "2",
          label: "管理员",
        },
      ],
      // 接收的用户列表数据
      list: null,
      // 控制加载动画
      loading: {
        list: false,
        add: false,
      },

      dialog: {
        add: false,
        view: false,
      },

      downloadLoading: false,
    };
  },
  methods: {
    getDateTime(value) {
      if (value) {
        this.listQuery.startTime = value[0];
        this.listQuery.endTime = value[1];
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },
    //导出
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "序号",
          "id",
          "昵称",
          "手机号",
          "地址",
          "金额（元）",
          "赠送金额（元）",
          "用户类型",
          "状态",
          "创建时间",
        ];
        const filterVal = [
          "index",
          "userId",
          "nickName",
          "userPhone",
          "address",
          "amountInfo",
          "givenAmountInfo",
          "userTypeInfo",
          "isFlagInfo",
          "ctime",
        ];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "用户列表",
        });
        this.downloadLoading = false;
      });
    },
    // 数据筛选
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    //获取用户列表
    async getList() {
      this.loading.list = true;
      try {
        //调用服务器接口
        const { data } = await getList({
          ...this.listQuery,
        });
        this.list = data.records.map((item, index) => ({
          index: index + 1,
          amountInfo: item.amount / 100,
          address: item.province + item.city + item.area,
          givenAmountInfo: item.givenAmount / 100,
          userTypeInfo: item.userType == 1 ? "普通用户" : "管理员",
          isFlagInfo: item.isFlag == 1 ? "启用 " : "禁用",
          ...item,
        }));
        this.total = data.total;
      } catch (error) {}
      this.loading.list = false;
    },
    //禁用启用
    changeStatus(userId, status) {
      let type;
      if (status) {
        type = status == 1 ? "启用" : "禁用";
      } else {
        type = "启用";
      }

      this.$confirm(`确定${type}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //调用服务器接口
          const { data } = await updateIsFlagUsers({
            userId: userId,
            isFlag: status,
          });
          this.$message({
            type: "success",
            message: `${type}成功!`,
          });
          this.getList();
        })
        .catch(() => {});
    },

    //搜索
    handleFilter() {
      this.listQuery.offset = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.offset = val;
      this.getList();
    },
  },
  //开启页渲染
  created() {
    this.getList();
  },
};
</script>
